package com.zmx.service.impl;

import com.alibaba.druid.sql.dialect.odps.ast.OdpsAddStatisticStatement;
import com.zmx.utils.RUtils;
import com.zmx.entity.SysMenu;
import com.zmx.mapper.SysMenuMapper;
import com.zmx.service.SysMenuService;
import org.springframework.stereotype.Service;
import sun.plugin.com.Utils;
import sun.security.util.ManifestEntryVerifier;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 2020/10/20
 * 10:11
 * zmx
 */
@Service("SysMenuService")
public class SysMenuServiceImpl implements SysMenuService {
    @Resource
    SysMenuMapper sysMenuMapper;
    @Override
    public List<SysMenu> finAllMenu(long userId,long parentId,int type) {
        List<SysMenu> allMenu = sysMenuMapper.findAllMenu(userId, parentId, 0);
        System.out.println(allMenu);
        for (SysMenu menu : allMenu) {
            menu.setList(sysMenuMapper.findAllMenu(userId, menu.getMenuId(), 1));
        }

        return allMenu;
    }

    @Override
    public Set<String> finPermsByUid(long userId) {
        List<String> permsByUid = sysMenuMapper.findPermsByUid(userId);
        Set<String> perms = new HashSet<>();
        for (String p : permsByUid) {
            if (p != null) {
                String[] split = p.split(",");
                for (String s : split) {
                    perms.add(s);
                }
            }
        }
        return perms;
    }

    @Override
    public RUtils findMenuByPage(Integer limit, Integer offset, String search, String order) {
        List<SysMenu> list = sysMenuMapper.findMenuByPage(limit, offset, search, order);
        long total = sysMenuMapper.findMenuTotal(search);
        return RUtils.success("成功",null).put("total",total).put("rows",list);
    }

    @Override
    public RUtils findAllTree() {
        List<SysMenu> allTree = sysMenuMapper.findAllTree();
        /*新建一个顶级目录 ，让type等于0的目录也可以使用*/
        SysMenu sysMenu = new SysMenu();
        sysMenu.setMenuId((long) 0);
        sysMenu.setName("定义目录");
        sysMenu.setParentId(-1L);
        allTree.add(sysMenu);
        return RUtils.success("成功",null).put("menuList",allTree);
    }

    @Override
    public RUtils saveMenu(SysMenu sysMenu) {
        int insert = sysMenuMapper.saveMenu(sysMenu);
        return insert>0?RUtils.success("添加成功",null):RUtils.fail("添加失败",null);
    }

    @Override
    public RUtils deleteFake(List<Long> ids) {
        sysMenuMapper.fakeDeleteByIds(ids);
        return RUtils.success("删除成功",null);
    }

    @Override
    public RUtils selectByMenuId(long id) {
        return RUtils.success("查询成功",null).put("menu",sysMenuMapper.findMenuById(id));
    }

    @Override
    public RUtils updateMenu(SysMenu sysMenu) {
        int i = sysMenuMapper.updateMenu(sysMenu);
        return i>0?RUtils.success("更新成功",null):RUtils.fail("更新失败",null);
    }

}
